package controllers

import (
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"time"
	"user_manage_sys/models"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Create() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	var user models.User
	user.UserName = c.GetString("name")
	if err := user.GetUserByUserName(); err != nil {
		c.Data["json"] = models.Msg{
			Code: 500,
			Msg:  "服务器繁忙，请稍后再试",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if user.ID != 0 {
		c.Data["json"] = models.Msg{
			Code: 201,
			Msg:  "账号已存在",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	user.UserPassword = c.GetString("password")

	if err := user.CreateUser(); err != nil {
		c.Data["json"] = models.Msg{
			Code: 500,
			Msg:  "服务器繁忙，请稍后再试",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.Msg{
		Code: 200,
		Msg:  "账号创建成功",
		Data: user,
	}
	c.ServeJSON()
}
func (c *UserController) Login() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	var user models.User
	user.UserName = c.GetString("name")
	password := c.GetString("password")
	key := fmt.Sprintf("From_Login_UserName:%s", user.UserName)
	count, _ := models.Rdb.Get(models.Ctx, key).Int()
	if count > 2 {
		models.Rdb.Expire(models.Ctx, key, 5*time.Minute)
		c.Data["json"] = models.Msg{
			Code: 202,
			Msg:  "密码错误次数过多，账号锁定五分钟",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if err := user.GetUserByUserName(); err != nil {
		c.Data["json"] = models.Msg{
			Code: 500,
			Msg:  "服务器繁忙，请稍后再试",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if user.ID == 0 {
		c.Data["json"] = models.Msg{
			Code: 201,
			Msg:  "账号不存在",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if user.UserPassword != password {
		models.Rdb.Incr(models.Ctx, key)
		c.Data["json"] = models.Msg{
			Code: 202,
			Msg:  "账号或密码错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.Msg{
		Code: 200,
		Msg:  "登陆成功",
		Data: nil,
	}
	c.ServeJSON()
}
